<?php
require_once(dirname(__FILE__).'/../config/db_connect.php');
//require_once(dirname(__FILE__).'/../service/service.cl.php');

class GuardUnit {

    private $error = array();
    private $label;
    private $start_date;
    private $end_date; 
    private $type; 
    private $id;
    private $alert;
    private $success = array();
   
    const WEEK = 'WEEK';
    const NATHOLIDAY = 'NATIONALHOLIDAY';
    const WEEKEND = 'WEEKEND';
    const RELHOLIDAY = 'RELIGIOUSHOLIDAY';

    public function setValues($data) {

       $this->id =  empty($data['id']) ? '' : strip_tags(trim($data['id']));
       $this->label = empty($data['label']) ? '' : strip_tags(trim($data['label']));
       $this->start_date =  empty($data['start_date']) ? '' : strip_tags(trim($data['start_date']));
       $this->end_date = empty($data['end_date']) ? '' : strip_tags(trim($data['end_date']));
       $this->type = empty($data['type']) ? '' : strip_tags(trim($data['type']));
       
    }
    public function reset() {

       $this->id ='';  
       $this->label = '';
       $this->start_date ='';
       $this->end_date = '';
       $this->type ='';        
    }

    public function save($data) {
      $this->setValues($data);
        if($this->getId()) {
            if($this->validate()) {
                $update="UPDATE guard_unit SET label='".mysql_real_escape_string($this->label)."', start_date='$this->start_date' , end_date='$this->end_date' , type='$this->type' WHERE id='$this->id' ";
                //debug($update);
                mysql_query ($update);
                //return $this->getguard_unit(mysql_insert_id());
            }
        } else {
            if($this->validate()) {
                mysql_query ("INSERT INTO guard_unit VALUES ('', '".mysql_real_escape_string($this->label)."', '".$this->start_date."','".$this->end_date."',
                 '".$this->type."')");
                $this->reset();
                //return $this->getguard_unit(mysql_insert_id());
            }
  
         }
    }

    public function loadGuardUnitById($id) {
        
        $select = "SELECT * FROM guard_unit WHERE id = '$id'";
        $resource = mysql_query($select);
        $this->setValues(mysql_fetch_array($resource));
    }
     public function getAllGuardUnits($type='') {
        
        $whereType = '';
        if($type == self::WEEK || $type == self::WEEKEND || $type == self::NATHOLIDAY || $type == self::RELHOLIDAY) {
            $whereType = " AND (type='$type') ";
        }

        $select = "SELECT * FROM guard_unit WHERE start_date LIKE '".date('Y')."%' ORDER BY start_date";
        $resource = mysql_query($select);
        if(mysql_num_rows($resource) > 0) {
            $select = "SELECT * FROM guard_unit WHERE (start_date LIKE '".date('Y')."%' OR start_date = '0000-00-00') $whereType ORDER BY start_date";
            $resource = mysql_query($select);
            $guardUnits = array();
            while($guardUnit = mysql_fetch_object($resource)) {
                  $guardUnits[] = $guardUnit;
            } 
            return $guardUnits; 
        } else {
            return array();
        }
    }

     public function getAllGuardUnitsWhereType($whereType='') {
        
        $select = "SELECT * FROM guard_unit WHERE (start_date LIKE '".date('Y')."%' OR start_date = '0000-00-00') AND $whereType ORDER BY start_date";
        $resource = mysql_query($select);

        $guardUnits = array();
        while($guardUnit = mysql_fetch_object($resource)) {
              $guardUnits[] = $guardUnit;
        } 
        return $guardUnits; 
    }

    private function validate() {

       if (empty($this->label)) {
           $this->addError("label","Saisissez le libellé");
       }
       if (empty($this->start_date)) {
           $this->addError("start_date","Choisisser  le la date de debut");
       }
       if (empty($this->end_date)) {
           $this->addError("end_date","Choisisser le la date de fin");
       }
       if (empty($this->type)) {
           $this->addError("type","Selectionner un type");
       }
       if(count($this->error) > 0) {
            return false;
        } else {
            return true;
        } 
    }

    private function addError($index, $error) {
        $this->error[$index] =  $error;
    }

    public function getError($index) { 
      if(!empty($this->error[$index])) {
        return '<div class="alert alert-error">'.$this->error[$index].'</div>';
      }
    }
    public function hasError() {
       return count($this->error) > 0 ? true : false;
    }
    public function getLabel(){
        return $this->label;
    }
    public function getStartDate(){
        return $this->start_date;
    }
    public function getEndDate(){
        return $this->end_date;
    }
    public function getType(){
        return $this->type;
    }
    public function getId(){
        return $this->id;
    }
    public function getAlert(){
        return $this->alert;
    }
    public function getSuccess(){
        return $this->success;
    }
    public function checkGuardUnit() {
    
        $selectWeek = "SELECT * FROM guard_unit WHERE start_date >= '".date('Y')."-01-01' AND end_date > '".date('Y')."-01-01' AND type='".self::WEEK."'";
        if(mysql_num_rows(mysql_query($selectWeek)) < 51) {
            $this->createWeeks();
            $this->success[] = 'Les dates des semaines ont été générées avec succès.';
        }

        $selectWeekend = "SELECT * FROM guard_unit WHERE start_date >= '".date('Y')."-01-01' AND end_date > '".date('Y')."-01-01' AND type='".self::WEEKEND."'";
        mysql_num_rows(mysql_query($selectWeekend));
        if(mysql_num_rows(mysql_query($selectWeekend)) < 51) {
            $this->createWeekEnds();
            $this->success[] = 'Les dates des weekend ont été générées avec succès.';
        }

        $selectNat = "SELECT * FROM guard_unit WHERE start_date >= '".date('Y')."-01-01' AND end_date >= '".date('Y')."-01-01' AND type='".self::NATHOLIDAY."'";
        if(mysql_num_rows(mysql_query($selectNat)) < 9) {
            $this->createNatHoliDay();
            $this->success[] = 'Les dates des fêtes nationales ont été générées avec succès.';
        }

        $selectRel = "SELECT * FROM guard_unit WHERE start_date >= '".date('Y')."-01-01' AND end_date >= '".date('Y')."-01-01' AND type='".self::RELHOLIDAY."'";
        $selectRelNodate = "SELECT * FROM guard_unit WHERE start_date='0000-00-00' OR end_date='0000-00-00' AND type='".self::RELHOLIDAY."'";
        $resultNodate = mysql_num_rows(mysql_query($selectRelNodate));
        if(mysql_num_rows(mysql_query($selectRel)) < 4  && $resultNodate == 0) {
            $this->createRelHoliDay();
            $this->success[] = 'Les fêtes religieuses ont été générées avec succès.';
        }
        
        $this->checkRelHoliDay();
    }
 
    public function checkRelHoliDay() {

        $selectRelNodate = "SELECT * FROM guard_unit WHERE start_date='0000-00-00' OR end_date='0000-00-00' AND type='".self::RELHOLIDAY."'";
        $resultNodate = mysql_num_rows(mysql_query($selectRelNodate));
        if($resultNodate > 0) {
            $this->alert = 'Les dates des fêtes religieuses ne sont pas encore définis.';
        }
    }


    public function createWeeks() {
          
        $dates  = array();
        $w = 5; 
        $nbDayPerYear = (date('j',mktime(0, 0, 0, 3, 0, date('Y'))) == 28) ? 365: 366;
        $i = 0;

        for($i; $i <= 7; $i++) {
            $dayWeek = date("w", mktime(19, 0, 0, 1, $i, date('Y')));
            if($dayWeek == $w) {
              break;
            }
        }
        $j=1;
        for($i; $i <= $nbDayPerYear; $i+=7) {  
            $d1 = date("Y-m-d" , mktime(7, 0, 0, 1, $i, date('Y')));
            $d2 = date("Y-m-d" , mktime(7, 0, 0, 1, $i+7, date('Y')));
            $this->insert('Semaine '.($j++), $d1, $d2, self::WEEK);
        }
    }

    /**
    *
    * Création des weenkends
    */
    public function createWeekEnds() {
          
        $dates  = array();
        $w = 6; 
        $nbDayPerYear = (date('j',mktime(0, 0, 0, 3, 0, date('Y'))) == 28) ? 365: 366;
        $i=0;
        for($i; $i <= 7; $i++) {
          $dayWeek = date("w", mktime(12, 0, 0, 1, $i, date('Y')));
          if($dayWeek == $w) {
              break;
          }
        }
        $j=1;
        for($i; $i <= $nbDayPerYear; $i+=7) {  
            $d1 = date("Y-m-d" , mktime(7, 0, 0, 1, $i, date('Y')));
            $d2 = date("Y-m-d" , mktime(7, 0, 0, 1, $i+1, date('Y')));
            $this->insert('Weekend '.($j++), $d1, $d2, self::WEEKEND);
        }
    }

    private function insert($label, $startDate, $endDate, $type) {

        $select = "SELECT * FROM guard_unit WHERE label='".mysql_real_escape_string($label)."' AND start_date='$startDate' AND end_date='$endDate' AND type='$type'";
        $resource = mysql_query($select);
        if(mysql_num_rows($resource) == 0) {
            mysql_query("INSERT INTO guard_unit VALUES('','".mysql_real_escape_string($label)."','$startDate','$endDate','$type')");
            return mysql_insert_id();
        }
    }

    public function createNatHoliDay() {

        $holyDays = $this->getYearNationalHoliDays();
        foreach($holyDays as $holyDay) {
            $this->insert($holyDay[0], $holyDay[1], $holyDay[1], self::NATHOLIDAY);
        }
    }

    public function createRelHoliDay() {

        $holyDays = $this->getYearReligiousHolidays();
        foreach($holyDays as $holyDay) {
            $this->insert($holyDay, '0000-00-00', '0000-00-00', self::RELHOLIDAY);
        }
    }

    public function getYearNationalHoliDays() {

        return  array(
           	 array("1er jour de l'an",date('Y')."-01-01"),
             array("Le Manifeste de l'Indépendance" , date('Y')."-01-11"),
             array("Fête du Travail" , date('Y')."-05-01"),
             array("Fête du Trône" , date('Y')."-07-30"),
             array("Fête de Oued Eddahab" , date('Y')."-08-14"),
             array("La Révolution du Roi et du Peuple" , date('Y')."-08-20"),
             array("Fête de la Jeunesse",date('Y')."-08-21"),
             array("La Marche Verte",date('Y')."-11-6"),
             array("Fête de l'Indépendance",date('Y')."-11-18"));   
     }

    public function getYearReligiousHolidays() {

       return array(
       	 "Fête de la Rupture du Jeûne",
         "Fête du Sacrifice",
         "Naissance du Prophète Mohammad",
         "1er Jour de l'An Higri");
    }
}
